package com.example.filter;

import com.example.common.JwtUtils;
import com.example.config.TenantContext;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求头中的Authorization字段，即token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            // 去掉token前缀，解析token，获取用户名和角色信息
            token = token.substring(7);
            Claims claims = jwtUtils.parseToken(token);
            String username = claims.getSubject();
            List<String> roles = claims.get("perms", List.class);
            Long currentTenantId = claims.get("current_tenant_id", Long.class);
            // 如果token有效，构造一个UsernamePasswordAuthenticationToken对象，设置到SecurityContext中，用于授权判断
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, getAuthorities(roles));
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                TenantContext.setTenant(currentTenantId);
            }
        }
        // 继续执行下一个过滤器
        filterChain.doFilter(request, response);
    }

    // 将用户的角色转换为GrantedAuthority对象的集合，用于授权判断
    private Collection<? extends GrantedAuthority> getAuthorities(List<String> perms) {
        return perms.stream().map(perm -> new SimpleGrantedAuthority(perm)).collect(Collectors.toList());
//        return null;
    }

}

